package com.stylefeng.guns.modular.owBackstageMgr.newsMgr.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.system.model.News;
import com.stylefeng.guns.modular.system.warpper.NewsWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.owBackstageMgr.newsMgr.service.INewsService;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 官网新闻管理控制器
 *
 * @author fengshuonan
 * @Date 2018-06-14 10:02:23
 */
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController {

    private String PREFIX = "/newsMgr/news/";

    @Autowired
    private INewsService newsService;

    /**
     * 跳转到官网新闻管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "news.html";
    }

    /**
     * 跳转到添加官网新闻管理
     */
    @RequestMapping("/news_add")
    public String newsAdd() {
        return PREFIX + "news_add.html";
    }

    /**
     * 跳转到修改官网新闻管理
     */
    @RequestMapping("/news_update/{newsId}")
    public String newsUpdate(@PathVariable Integer newsId, Model model) {
        News news = newsService.selectById(newsId);
        model.addAttribute("news",news);
        LogObjectHolder.me().set(news);
        return PREFIX + "news_edit.html";
    }

    /**
     * 获取官网新闻管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) String title) {
        Page<News> page = new PageFactory<News>().defaultPage();
        List<Map<String, Object>> result = newsService.getNewsList(page, beginTime, endTime, title,  page.getOrderByField(), page.isAsc());
        page.setRecords((List<News>) new NewsWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * 新增官网新闻管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(News news) {
        if (ToolUtil.isOneEmpty(news, news.getTitle())) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        // 新闻创建时间是后台设置的时候，更新时间与之相同;非后台设置，则两者都为当前时间
        if (news.getCreateTime() != null){
            news.setUpdateTime(news.getCreateTime());
        }else {
            news.setCreateTime(new Date());
            news.setUpdateTime(new Date());
        }

        news.setTitle(news.getTitle().replace("& lt;","<").replace("& gt;",">")
                .replace("& #40;","(").replace("& #41;",")"));

        // 新闻内容传到后台尖括号会变成字符实体，故作转换
        news.setContent(news.getContent().replace("& lt;","<").replace("& gt;",">")
                .replace("& #40;","(").replace("& #41;",")"));

        // 查找已经是“置顶”状态的新闻的主键id
        Long topNewsId = newsService.getTheTopNewsId(news.getCategory());

        // 需要进行“置顶”
        if (news.getIsTop() == 1){
            // 某一类别下已经有旧的置顶新闻，需要将旧的去掉置顶状态，设置新的新闻为置顶状态
            if (topNewsId != null){
                newsService.setNewsIsNotTop(topNewsId);
                news.setIsTop(1);
            }else {
                news.setIsTop(1);
            }
        }

        news.insert();
        return SUCCESS_TIP;
    }

    /**
     * 删除官网新闻管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer newsId) {
        if (newsId != null){
            News news = newsService.selectById(newsId);
            if (news != null){
                news.setUpdateTime(new Date());
                news.setIsDel(1);// 表示删除状态
                news.updateById();
                return SUCCESS_TIP;
            }else {
                return new ErrorTip(-1,"找不到需要删除的记录");
            }
        }
        return new ErrorTip(-1,"参数错误");
    }

    /**
     * 修改官网新闻管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(News news) {
        if (ToolUtil.isOneEmpty(news, news.getId(), news.getTitle(), news.getCategory())) {
            throw new GunsException(BizExceptionEnum.REQUEST_NULL);
        }

        News old = this.newsService.selectById(news.getId());
        old.setParentTitle(news.getParentTitle());
        old.setTitle(news.getTitle().replace("& lt;","<").replace("& gt;",">").replace("& #40;","(").replace("& #41;",")"));
        old.setContent(news.getContent().replace("& lt;","<").replace("& gt;",">").replace("& #40;","(").replace("& #41;",")"));
        old.setCategory(news.getCategory());

        // 新闻的“附带图片”如果进行修改则更新为新的图片，如果没有则保持原来的图片链接
        if (!ToolUtil.isEmpty(news.getPicture())){
            old.setPicture(news.getPicture());
        }

        old.setDescription(news.getDescription());
        old.setTransmitFrom(news.getTransmitFrom());
        old.setAuthor(news.getAuthor());
        old.setIsShow(news.getIsShow());
        old.setExternalLink(news.getExternalLink());

        // 查找已经是“置顶”状态的新闻的主键id
        Long topNewsId = newsService.getTheTopNewsId(news.getCategory());

        // 需要进行“置顶”
        if (news.getIsTop() == 1){
            if (topNewsId != null){
                // ② 已经“置顶”的新闻非当前需要进行置顶操作的新闻时，才进行更新
                if (topNewsId != news.getId()){
                    // 某一类别下已经有旧的置顶新闻，需要将旧的去掉置顶状态，设置新的新闻为置顶状态
                    newsService.setNewsIsNotTop(topNewsId);
                    old.setIsTop(1);
                }
            }else {
                old.setIsTop(1);
            }
        }

        old.setOrderval(news.getOrderval());
        old.setIsTop(news.getIsTop());
        old.setKeyword(news.getKeyword());
        old.setReadtimes(news.getReadtimes());

        // 手动设置新闻创建时间则需要更新create_time字段
        if (ToolUtil.isNotEmpty(old.getCreateTime())){
            old.setCreateTime(news.getCreateTime());
        }
        old.setUpdateTime(new Date());
        old.updateById();

        return SUCCESS_TIP;
    }

    /**
     * 官网新闻管理详情
     */
    @RequestMapping(value = "/detail/{newsId}")
    @ResponseBody
    public Object detail(@PathVariable("newsId") Integer newsId) {
        if (newsId != null){
            News news = newsService.selectById(newsId);
            if (news != null){
                return news;
            }else {
                return new ErrorTip(-1,"找不到需要查看详情的记录");
            }
        }else{
            return new ErrorTip(-1,"传入的参数错误");
        }
    }
}
